import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Form, Input, Select, message, Popconfirm, Card, Tree } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MenuOutlined } from '@ant-design/icons';

const { Option } = Select;

interface MenuItem {
  id: number;
  name: string;
  path: string;
  icon: string;
  sort: number;
  type: 'menu' | 'button';
  parentId: number | null;
  status: 'active' | 'inactive';
  permission?: string;
  createTime: string;
  children?: MenuItem[];
}

const MenuManagement: React.FC = () => {
  const [menus, setMenus] = useState<MenuItem[]>([]);
  const [flatMenus, setFlatMenus] = useState<MenuItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState<MenuItem | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    loadMenus();
  }, []);

  const loadMenus = async () => {
    setLoading(true);
    try {
      // 模拟 API 调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      const mockData: MenuItem[] = [
        {
          id: 1,
          name: '仪表板',
          path: '/dashboard',
          icon: 'DashboardOutlined',
          sort: 1,
          type: 'menu',
          parentId: null,
          status: 'active',
          createTime: '2023-01-01',
        },
        {
          id: 2,
          name: '用户管理',
          path: '/user',
          icon: 'UserOutlined',
          sort: 2,
          type: 'menu',
          parentId: null,
          status: 'active',
          createTime: '2023-01-01',
          children: [
            {
              id: 3,
              name: '用户列表',
              path: '/user/list',
              icon: '',
              sort: 1,
              type: 'menu',
              parentId: 2,
              status: 'active',
              createTime: '2023-01-01',
            },
            {
              id: 4,
              name: '用户详情',
              path: '/user/profile/:id',
              icon: '',
              sort: 2,
              type: 'menu',
              parentId: 2,
              status: 'active',
              createTime: '2023-01-01',
            },
          ],
        },
        {
          id: 5,
          name: '系统管理',
          path: '/system',
          icon: 'SettingOutlined',
          sort: 3,
          type: 'menu',
          parentId: null,
          status: 'active',
          createTime: '2023-01-01',
          children: [
            {
              id: 6,
              name: '角色管理',
              path: '/system/role',
              icon: '',
              sort: 1,
              type: 'menu',
              parentId: 5,
              status: 'active',
              createTime: '2023-01-01',
            },
            {
              id: 7,
              name: '菜单管理',
              path: '/system/menu',
              icon: '',
              sort: 2,
              type: 'menu',
              parentId: 5,
              status: 'active',
              createTime: '2023-01-01',
            },
          ],
        },
      ];
      setMenus(mockData);
      setFlatMenus(flattenMenus(mockData));
    } catch (error) {
      message.error('加载菜单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const flattenMenus = (menus: MenuItem[]): MenuItem[] => {
    const result: MenuItem[] = [];
    
    const flatten = (items: MenuItem[]) => {
      items.forEach(item => {
        result.push({ ...item, children: undefined });
        if (item.children) {
          flatten(item.children);
        }
      });
    };
    
    flatten(menus);
    return result;
  };

  const buildTreeData = (menus: MenuItem[]): any[] => {
    return menus
      .filter(menu => !menu.parentId)
      .map(menu => ({
        key: menu.id,
        title: (
          <span>
            <MenuOutlined style={{ marginRight: 8 }} />
            {menu.name}
            <Tag color="blue" style={{ marginLeft: 8 }}>{menu.path}</Tag>
          </span>
        ),
        children: menu.children ? buildTreeData(menu.children) : undefined,
      }));
  };

  const handleAdd = () => {
    setEditingMenu(null);
    setModalVisible(true);
    form.resetFields();
  };

  const handleEdit = (menu: MenuItem) => {
    setEditingMenu(menu);
    setModalVisible(true);
    form.setFieldsValue(menu);
  };

  const handleDelete = async (id: number) => {
    try {
      // 模拟删除
      await new Promise(resolve => setTimeout(resolve, 500));
      const deleteRecursive = (menus: MenuItem[]): MenuItem[] => {
        return menus.filter(menu => {
          if (menu.id === id) return false;
          if (menu.children) {
            menu.children = deleteRecursive(menu.children);
          }
          return true;
        });
      };
      setMenus(deleteRecursive(menus));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      // 这里实现添加/更新逻辑
      message.success(editingMenu ? '更新成功' : '添加成功');
      setModalVisible(false);
      loadMenus(); // 重新加载
    } catch (error) {
      message.error('操作失败');
    }
  };

  const columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Tag color={type === 'menu' ? 'blue' : 'green'}>
          {type === 'menu' ? '菜单' : '按钮'}
        </Tag>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Tag color={status === 'active' ? 'green' : 'red'}>
          {status === 'active' ? '激活' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: MenuItem) => (
        <Space size="middle">
          <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定删除这个菜单吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加菜单
          </Button>
        </div>

        <div style={{ display: 'flex', gap: 24 }}>
          <div style={{ flex: 1 }}>
            <h4>菜单树形结构</h4>
            <Tree
              showLine
              defaultExpandAll
              treeData={buildTreeData(menus)}
            />
          </div>
          
          <div style={{ flex: 2 }}>
            <h4>菜单列表</h4>
            <Table
              columns={columns}
              dataSource={flatMenus}
              rowKey="id"
              loading={loading}
              pagination={false}
            />
          </div>
        </div>
      </Card>

      <Modal
        title={editingMenu ? '编辑菜单' : '添加菜单'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={500}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="菜单名称"
            name="name"
            rules={[{ required: true, message: '请输入菜单名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="菜单路径"
            name="path"
            rules={[{ required: true, message: '请输入菜单路径' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="图标"
            name="icon"
          >
            <Input placeholder="例如: UserOutlined" />
          </Form.Item>

          <Form.Item
            label="父级菜单"
            name="parentId"
          >
            <Select placeholder="选择父级菜单">
              <Option value={null}>作为一级菜单</Option>
              {flatMenus.filter(menu => menu.type === 'menu').map(menu => (
                <Option key={menu.id} value={menu.id}>
                  {menu.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="类型"
            name="type"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select>
              <Option value="menu">菜单</Option>
              <Option value="button">按钮</Option>
            </Select>
          </Form.Item>

          <Form.Item
            label="排序"
            name="sort"
            rules={[{ required: true, message: '请输入排序号' }]}
          >
            <Input type="number" />
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value="active">激活</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                {editingMenu ? '更新' : '添加'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuManagement;